package com.bootcamp.servlet.mvc.controller;

/**
 * @program: wrok-1101
 * @author: Keyu Li
 * @create: 2021-11-05 20:22
 **/

import com.bootcamp.servlet.mvc.dao.CustomDao;
import com.bootcamp.servlet.mvc.dao.CustomJSONDao;
import com.bootcamp.servlet.mvc.model.Custom;
import com.bootcamp.servlet.mvc.model.CustomWithInfo;
import com.bootcamp.servlet.mvc.utils.CartUtils;
import com.bootcamp.servlet.mvc.utils.PrintHeadByAuthUtils;
import com.bootcamp.servlet.mvc.utils.ShopFootprintUtils;
import com.bootcamp.servlet.mvc.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/user/*")
public class LoginServlet extends HttpServlet {
    CustomDao customDao = new CustomJSONDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace(request.getContextPath() + "/user/", "");
        HttpSession session = request.getSession();

        if ("logoff".equals(op)) {
            Custom custom = (Custom) session.getAttribute("custom");
            if (custom == null) {
                failWithReason("保存信息失败！", request, response);
                return;
            }
            customDao.storeCustomInfo(session);
            session.invalidate();
            success("保存信息成功！正在退出ing", request, response);
        } else if ("homepage".equals(op)) {
            opHomepage(request, response);
            customDao.storeCustomInfo(session);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        Custom custom = new Custom();

        // 获取op为register或login
        String op = request.getRequestURI().replace(request.getContextPath() + "/user/", "");

        if ("register".equals(op)) {
            opRegister(request, response, custom);
        }

        // 为login，先校验 密码及用户名 为英文+数字
        else if ("login".equals(op)) {
            opLogin(request, response, custom);
        }

    }

    private void opHomepage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 展示个人主页，含 头行，购物车，历史足迹
        PrintHeadByAuthUtils.printHead(request, writer);
        // 打印个性签名
        writer.println("<h2>个性签名</h2>");
        Custom custom = (Custom) request.getSession().getAttribute("custom");
        String description = custom.getDescription();
        writer.println("<div>" + description + "</div>");
        // 打印购物车
        writer.println("<h2>购物车</h2>");
        CartUtils.printCart(request, response);
        // 打印历史足迹
        writer.println("<h2>历史足迹</h2>");
        ShopFootprintUtils.printFootprint(request, response);
    }


    private boolean opRegister(HttpServletRequest request, HttpServletResponse response, Custom custom) throws IOException {
        // 为register，先校验密码及确认密码正码，及密码和用户名为 英文+数字
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String ackPassword = request.getParameter("ackPassword");
        String description = request.getParameter("description");
        if (!StringUtils.isEnglishAndNumber(username)) {
            failWithReason("注册失败！ 用户名非法，请选择字母+数字", request, response);
            return false;
        }
        if (!StringUtils.isEnglishAndNumber(password)
                || !StringUtils.isEnglishAndNumber(ackPassword)) {
            failWithReason("注册失败！ 密码非法，请选择字母+数字", request, response);
            return false;
        }
        if (username.length() < 3 || username.length() > 20) {
            failWithReason("注册失败！ 用户名长度非法，请在 3-20 位之间", request, response);
            return false;
        }
        if (!password.equals(ackPassword)) {
            failWithReason("注册失败！ 两次密码不一致！", request, response);
            return false;
        }
        if (password.length() < 8 || password.length() > 20) {
            failWithReason("注册失败！ 密码长度非法，请在 8-20 位之间", request, response);
            return false;
        }

        // 封装为custom对象，同 数据库/json 校验用户名唯一性
        custom.setUsername(username);
        custom.setPassword(password);
        if (StringUtils.isEmpty(description)) {
            description = "当前用户不想理你";
        }
        custom.setDescription(description);
        Integer registerStatus = customDao.register(custom);
        if (registerStatus.equals(404)) {
            failWithReason("注册失败！ 用户名重复", request, response);
            return false;
        }
        if (registerStatus.equals(500)) {
            failWithReason("注册失败！ 服务器错误，请联系管理员", request, response);
            return false;
        }
        if (registerStatus.equals(200)) {
            // 注册成功后，存储该对象到session
            HttpSession session = request.getSession();
            session.setAttribute("custom", custom);
            success("注册成功！", request, response);
            return true;
        }
        return false;
    }

    private boolean opLogin(HttpServletRequest request, HttpServletResponse response, Custom custom) throws IOException {
        // 封装为custom对象，同 数据库/json 校验登陆成功
        String userid = request.getParameter("userid");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 先进行简单合法性校验
        if (StringUtils.isEmpty(userid) && StringUtils.isEmpty(username)) {
            failWithReason("登陆失败！请输出id或用户名至少一项", request, response);
            return false;
        }
        if (!StringUtils.isEmpty(userid) && !StringUtils.isNumber(userid)) {
            failWithReason("登陆失败！非法id", request, response);
            return false;
        }
        if (!StringUtils.isEmpty(username) && !StringUtils.isEnglishAndNumber(username)) {
            failWithReason("登陆失败！非法用户名", request, response);
            return false;
        }
        if (!StringUtils.isEnglishAndNumber(password)) {
            failWithReason("登陆失败！密码错误", request, response);
            return false;
        }
        // 再通过json/数据库进行合法性校验
        Integer id = StringUtils.isEmpty(userid) ? null : Integer.parseInt(userid);
        custom.setId(id);
        custom.setUsername(username);
        custom.setPassword(password);
        CustomWithInfo customWithInfo = new CustomWithInfo();
        customWithInfo.setCustom(custom);
        Integer login = customDao.login(customWithInfo);
        if (login.equals(1)) {
            failWithReason("登陆失败！当前用户不存在", request, response);
            return false;
        }
        if (login.equals(2)) {
            failWithReason("登陆失败！密码错误", request, response);
            return false;
        }
        if (login.equals(3)) {
            failWithReason("登陆失败！服务器错误，请联系管理员", request, response);
            return false;
        }
        if (login.equals(0)) {
            // 将用户信息存储进session
            HttpSession session = request.getSession();
            session.setAttribute("custom", customWithInfo.getCustom());
            session.setAttribute("cartItem", customWithInfo.getCart());
            session.setAttribute("footprintMap", customWithInfo.getFootprintDate());
            session.setAttribute("footprintDeque", customWithInfo.getFootprint());
            success("登录成功！", request, response);
            return true;
        }
        return false;
    }

    private void success(String cong, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String storepage = request.getContextPath() + "/store/page";
        response.getWriter().println(cong + "\n正在跳转购物页面ing");
        response.setHeader("refresh", "1;url=" + storepage);
    }

    public void failWithReason(String reason, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String storepage = request.getContextPath() + "/store/page";
        response.getWriter().println(reason + "\n正在跳转购物页面ing");
        response.setHeader("refresh", "1;url=" + storepage);
    }


}
